<template>
  <div class="departments">
    <el-card class="card">
      <!-- <template #header>
        <div>组织架构</div>
      </template> -->
      <el-tabs>
        <el-tab-pane label="组织架构">
          <div class="main">
            <TreeItem :item="topItem" />
            <hr>
            <!-- 树形结构 -->
            <el-tree :data="treeData">
              <template v-slot="{ data }">
                <TreeItem :item="data" @getData="getData" />
                <!-- <div class="top" style="">
                  <div class="title">{{ data.name }}</div>
                  <div class="manager">{{ data.manager }}</div>
                  <el-dropdown>
                    <span>
                      操作
                      <i class="el-icon-arrow-down el-icon--right" />
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item>添加子部门</el-dropdown-item>
                        <el-dropdown-item>查看部门</el-dropdown-item>
                        <el-dropdown-item>删除部门</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div> -->
              </template>
            </el-tree>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 新增弹框组件 -->
    <Add :init-data="initData" @getData="getData" />
  </div>
</template>

<script>
import { companyDepartment } from '@/api/departments'
import TreeItem from './components/treeItem.vue'
import Add from './components/Add.vue'
export default {
  components: {
    TreeItem,
    Add
  },
  data() {
    return {
      treeData: [],
      initData: [],
      defaultProps: {
        name: 'label',
        children: 'children'
      },
      topItem: {
        name: '',
        manager: '负责人',
        id: '',
        isTop: true
      }
    }
  },
  async created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await companyDepartment()
      // 传递原始组件架构列表数据
      this.initData = res.data.depts
      this.treeData = this.changeData(res.data.depts, '')
      this.topItem.name = res.data.companyName
    },
    // 将数据转换为树形数据
    changeData(arr, pid) {
      return arr.filter((item) => {
        if (item.pid === pid) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.departments {
  padding: 20px;
  .card {
    padding: 40px;
    .main {
      padding: 0 60px;
      margin: 30px auto;
    }
  }
}
</style>
